<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="费率名称" prop="rateName">
        <el-input
          v-model="queryParams.rateName"
          placeholder="请输入费率名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="版本号" prop="versionNumber">
        <el-input
          v-model="queryParams.versionNumber"
          placeholder="请输入版本号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更新状态" prop="updateStatus">
        <el-select
          v-model="queryParams.updateStatus"
          placeholder="请选择更新状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.charge_rate_update_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下发状态" prop="deliveryStatus">
        <el-select
          v-model="queryParams.deliveryStatus"
          placeholder="请选择下发状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.charge_rate_delivery_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="预约状态" prop="appointmentStatus">
        <el-select
          v-model="queryParams.appointmentStatus"
          placeholder="请选择预约状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.charge_rate_appointment_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下发类型" prop="deliveryType">
        <el-select
          v-model="queryParams.deliveryType"
          placeholder="请选择下发类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.charge_rate_delivery_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="下发时间" prop="deliveryTime">
        <el-date-picker
          clearable
          v-model="queryParams.deliveryTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择下发时间"
        >
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:chargeRate:add']"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:chargeRate:edit']"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:chargeRate:remove']"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:chargeRate:export']"
          >导出</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="chargeRateList"
      @selection-change="handleSelectionChange"
      @expand-change="handleExpandChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-table
            :data="props.row.tableData"
            style="width: 100%"
            v-loading="loadingInfo"
          >
            <el-table-column prop="templateType" label="模板类型">
              <template slot-scope="scope">
                <dict-tag
                  :options="dict.type.charge_rate_detail_template_type"
                  :value="scope.row.templateType"
                />
              </template>
            </el-table-column>
            <el-table-column prop="startTime" label="开始时间">
            </el-table-column>
            <el-table-column prop="endTime" label="结束时间"> </el-table-column>
            <el-table-column prop="chargeCost" label="充电电费/元">
            </el-table-column>
            <el-table-column prop="serviceFee" label="充电服务费/元">
            </el-table-column>
          </el-table>
        </template>
      </el-table-column>
      <!-- <el-table-column label="费率ID" align="center" prop="rateId" /> -->
      <el-table-column label="费率名称" align="center" prop="rateName" />
      <el-table-column label="版本号" align="center" prop="versionNumber" />
      <el-table-column label="更新状态" align="center" prop="updateStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.charge_rate_update_status"
            :value="scope.row.updateStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="下发状态" align="center" prop="deliveryStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.charge_rate_delivery_status"
            :value="scope.row.deliveryStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="预约状态" align="center" prop="appointmentStatus">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.charge_rate_appointment_status"
            :value="scope.row.appointmentStatus"
          />
        </template>
      </el-table-column>
      <el-table-column label="下发类型" align="center" prop="deliveryType">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.charge_rate_delivery_type"
            :value="scope.row.deliveryType"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="下发时间"
        align="center"
        prop="deliveryTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            icon="el-icon-info"
            @click="handleDetail(scope.row)"
            v-hasPermi="['business:chargeRate:detail']"
            >详情</el-button
          > -->

          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:chargeRate:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:chargeRate:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改充电费率信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="费率名称" prop="rateName">
              <el-input v-model="form.rateName" placeholder="请输入费率名称" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="版本号" prop="versionNumber">
              <el-input
                v-model="form.versionNumber"
                placeholder="请输入版本号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="费率模版">
              <el-select
                style="width: 100%"
                v-model="toselectValue"
                placeholder="请选择费率模版"
                @change="changeTodata"
              >
                <el-option
                  v-for="item in dataToSelectList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="下发类型" prop="deliveryType">
              <el-select
                style="width: 100%"
                v-model="form.deliveryType"
                placeholder="请选择下发类型"
              >
                <el-option
                  v-for="dict in dict.type.charge_rate_delivery_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="8">
            <el-form-item
              label="下发时间"
              prop="deliveryTime"
              v-if="form.deliveryType == '10'"
            >
              <el-date-picker
                style="width: 100%"
                v-model="form.deliveryTime"
                type="datetime"
                placeholder="请选择下发时间"
                format="yyyy-MM-dd HH:mm:ss"
                @keyup.enter.native="handleQuery"
                value-format="yyyy-MM-dd HH:mm:ss"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <!-- 步骤2的表单：修改formInfo的model和校验配置 -->
      <el-form
        ref="formInfo"
        :model="{ formInfoList: formInfoList }"
        :rules="tableRules"
        label-width="100px"
      >
        <el-table :data="formInfoList" style="width: 100%" :key="tableKey" >
          <el-table-column label="序号" width="80" align="center">
            <template slot-scope="scope">
              <!-- 行索引 + 1，保证序号从1开始 -->
              <el-form-item label-width="0">
                {{ scope.row.sortNo }}
              </el-form-item>
            </template>
          </el-table-column>
          <!-- 1. 电价类型：绑定动态prop -->
          <el-table-column label="电价类型" prop="templateType" width="120">
            <template slot-scope="scope">
              <el-form-item
                :prop="`formInfoList[${scope.$index}].templateType`"
                :rules="tableRules.templateType"
                label-width="0"
              >
                <el-select
                  v-model="scope.row.templateType"
                  style="width: 100%"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="dict in dict.type.charge_rate_detail_template_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>

          <!-- 2. 开始时间：无需校验（固定不可改） -->
          <el-table-column label="开始时间" prop="startTime" width="180">
            <template slot-scope="scope">
              <el-form-item label-width="0">
                <el-time-select
                  style="width: 100%"
                  v-model="scope.row.startTime"
                  :picker-options="{
                    start: '00:00',
                    step: '00:30',
                    end: '24:00',
                  }"
                  :disabled="true"
                  placeholder="选择开始时间"
                ></el-time-select>
              </el-form-item>
            </template>
          </el-table-column>

          <!-- 3. 结束时间：绑定动态prop -->
          <el-table-column label="结束时间" prop="endTime" width="180">
            <template slot-scope="scope">
              <el-form-item
                :prop="`formInfoList[${scope.$index}].endTime`"
                :rules="tableRules.endTime"
                label-width="0"
              >
                <el-time-select
                  style="width: 100%"
                  v-model="scope.row.endTime"
                  :picker-options="getEndTimePickerOptions(scope.$index)"
                  :disabled="scope.row.isEndTimeFixed"
                  placeholder="请选择"
                  @change="handleEndTimeChange(scope.row, scope.$index)"
                ></el-time-select>
              </el-form-item>
            </template>
          </el-table-column>

          <!-- 4. 充电电费：绑定动态prop -->
          <el-table-column label="充电电费/元" prop="chargeCost">
            <template slot-scope="scope">
              <el-form-item
                :prop="`formInfoList[${scope.$index}].chargeCost`"
                :rules="tableRules.chargeCost"
                label-width="0"
              >
                <el-input
                  v-model="scope.row.chargeCost"
                  type="number"
                  step="0.01"
                  placeholder="请输入"
                />
              </el-form-item>
            </template>
          </el-table-column>

          <!-- 5. 充电服务费：绑定动态prop -->
          <el-table-column label="充电服务费/元" prop="serviceFee">
            <template slot-scope="scope">
              <el-form-item
                :prop="`formInfoList[${scope.$index}].serviceFee`"
                :rules="tableRules.serviceFee"
                label-width="0"
              >
                <el-input
                  v-model="scope.row.serviceFee"
                  type="number"
                  step="0.01"
                  placeholder="请输入"
                />
              </el-form-item>
            </template>
          </el-table-column>

          <!-- 操作列：不变 -->
          <el-table-column label="操作" width="120">
            <template slot-scope="scope">
              <el-form-item label-width="0">
                <el-button
                  v-if="scope.$index !== 0"
                  size="mini"
                  type="danger"
                  plain
                  icon="el-icon-delete"
                  class="table-delete-btn"
                  @click="deleteFormInfoRow(scope.$index)"
                ></el-button>
                <el-button
                  v-if="
                    (formInfoList.length === 1 && scope.$index === 0) ||
                    (formInfoList.length > 1 &&
                      scope.$index === formInfoList.length - 1 &&
                      formInfoList[formInfoList.length - 1].endTime !==
                        '24:00') ||
                    (formInfoList.length > 1 &&
                      scope.$index === formInfoList.length - 2 &&
                      formInfoList[formInfoList.length - 1].endTime === '24:00')
                  "
                  type="success"
                  plain
                  size="mini"
                  icon="el-icon-plus"
                  @click="addFormInfoRow(scope.$index)"
                ></el-button>
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormInfo(false)"
          >下发</el-button
        >
        <el-button type="success" @click="submitFormInfo(true)"
          >下发并保存为模版</el-button
        >
        <el-button @click="cancelInfo">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listChargeRate,
  getChargeRate,
  delChargeRate,
  addChargeRate,
  updateChargeRate,
  dataToSelect,
  getInfoByRateId,
} from "@/api/business/chargeRate";
export default {
  name: "ChargeRate",
  dicts: [
    "charge_rate_appointment_status",
    "charge_rate_delivery_type",
    "charge_rate_update_status",
    "charge_rate_delivery_status",
    "charge_rate_detail_template_type",
  ],
  data() {
    return {
      toselectValue: "",
      dataToSelectList: [],
      tableKey: new Date() + Math.random(),
      formInfoList: [
        {
          sortNo: 1,
          templateType: "10",
          startTime: "00:00", // 初始开始时间固定
          endTime: "06:00", // 初始结束时间
          chargeCost: null,
          serviceFee: null,
          isEndTimeFixed: false, // 标记结束时间是否可修改
        },
        {
          sortNo: 2,
          templateType: "11",
          startTime: "06:00", // 初始开始时间固定
          endTime: "12:00", // 初始结束时间
          chargeCost: null,
          serviceFee: null,
          isEndTimeFixed: false, // 标记结束时间是否可修改
        },
        {
          sortNo: 3,
          templateType: "10",
          startTime: "12:00", // 初始开始时间固定
          endTime: "14:00", // 初始结束时间
          chargeCost: null,
          serviceFee: null,
          isEndTimeFixed: false, // 标记结束时间是否可修改
        },
        {
          sortNo: 4,
          templateType: "11",
          startTime: "14:00", // 初始开始时间固定
          endTime: "24:00", // 初始结束时间
          chargeCost: null,
          serviceFee: null,
          isEndTimeFixed: true, // 标记结束时间是否可修改
        },
      ],
      loadingInfo:true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 充电费率信息表格数据
      chargeRateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        rateName: null,
        versionNumber: null,
        updateStatus: null,
        deliveryStatus: null,
        appointmentStatus: null,
        deliveryType: null,
        deliveryTime: null,
      },
      // 表单参数
      form: {},
      formInfo: {},
      // 表单校验
      rules: {
        rateName: [
          { required: true, message: "费率名称不能为空", trigger: "blur" },
        ],
        versionNumber: [
          { required: true, message: "版本号不能为空", trigger: "blur" },
        ],
        updateStatus: [
          { required: true, message: "更新状态不能为空", trigger: "change" },
        ],
        deliveryStatus: [
          { required: true, message: "下发状态不能为空", trigger: "change" },
        ],
        appointmentStatus: [
          { required: true, message: "预约状态不能为空", trigger: "change" },
        ],
        deliveryType: [
          { required: true, message: "下发类型不能为空", trigger: "change" },
        ],
        deliveryTime: [
          { required: true, message: "下发时间不能为空", trigger: "blur" },
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" },
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" },
        ],
      },
      tableRules: {
        // 电价类型：必填
        templateType: [
          { required: true, message: "请选择电价类型", trigger: "change" },
        ],
        // 结束时间：必填
        endTime: [
          { required: true, message: "请选择结束时间", trigger: "change" },
        ],
        // 充电电费：必填 + 0-100范围 + 最多4位小数
        chargeCost: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value <= 0 || value > 100) {
                callback(new Error("充电电费需在 0-100 之间"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
          {
            pattern: /^\d+(\.\d{1,4})?$/,
            message: "最多保留四位小数",
            trigger: "blur",
          },
        ],
        // 充电服务费：必填 + 0-100范围 + 最多4位小数
        serviceFee: [
          {
            required: true,
            validator: (rule, value, callback) => {
              if (value <= 0 || value > 100) {
                callback(new Error("充电服务费需在 0-100 之间"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
          {
            pattern: /^\d+(\.\d{1,4})?$/,
            message: "最多保留四位小数",
            trigger: "blur",
          },
        ],
      },
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /**
     * 动态生成结束时间选择器的配置（核心：控制选择范围和间隔）
     * @param {number} index - 当前行索引
     * @returns {Object} picker-options配置
     */
    getEndTimePickerOptions(index) {
      const currentRow = this.formInfoList[index];
      const hasNextRow = index < this.formInfoList.length - 1;
      const nextRow = hasNextRow ? this.formInfoList[index + 1] : null;

      // 1. 计算当前条的最小可选时间（下限）：当前行开始时间 + 30分钟
      let minStartTimeMinutes = this.timeToMinutes(currentRow.startTime);
      minStartTimeMinutes += 30;
      const minStartTime = this.minutesToTime(minStartTimeMinutes);

      // 2. 计算当前条的最大可选时间（上限）：下一条结束时间的前30分钟
      let maxEndMinutes = 1440; // 默认24:00（1440分钟 = 24*60）
      if (hasNextRow && nextRow.endTime) {
        const nextEndMinutes = this.timeToMinutes(nextRow.endTime);
        // 上限 = 下一条结束时间 - 30分钟（确保当前条 < 下一条）
        maxEndMinutes = nextEndMinutes - 30;
        // 防止上限小于当前行开始时间（极端情况，如 nextEndTime 是 00:30）
        maxEndMinutes = Math.max(maxEndMinutes, minStartTimeMinutes);
      }
      const maxEndTime = this.minutesToTime(maxEndMinutes);

      return {
        // 2. 选择范围：从当前行开始时间 + 30分钟 到 计算出的上限时间
        start: minStartTime,
        end: maxEndTime,

        // 3. 禁用非30分钟间隔的分钟（只允许 00/30 分）
        disabledMinutes: (selectedHour) => {
          // 先计算当前小时对应的总分钟数
          const currentHourMinutes = selectedHour * 60;
          // 过滤：只保留 00 和 30 分（且需在 [start, maxEndMinutes] 范围内）
          return [0, 30].filter((minute) => {
            const totalMinutes = currentHourMinutes + minute;
            // 分钟需满足：>= 最小可选时间分钟数 && <= 上限分钟数
            return (
              totalMinutes >= minStartTimeMinutes &&
              totalMinutes <= maxEndMinutes
            );
          }).length === 0
            ? [0, 1, 2, ...59] // 若该小时无可用分钟，禁用所有
            : [1, 2, ...29, 31, ...59]; // 否则禁用非00/30的分钟
        },

        // 4. 禁用超过上限时间的小时（如上限是23:30，禁用24点及以后）
        disabledHours: () => {
          const maxHour = Math.floor(maxEndMinutes / 60);
          const disabledHours = [];
          // 禁用超过上限小时的所有小时（如 maxHour=23，禁用24）
          for (let i = maxHour + 1; i < 24; i++) {
            disabledHours.push(i);
          }
          return disabledHours;
        },
      };
    },
    /**
     * 时间字符串转分钟数（如 "06:00" → 360）
     * @param {string} time - 格式 "HH:mm"
     * @returns {number} 分钟数
     */
    timeToMinutes(time) {
      if (!time) return 0;
      const [hours, minutes] = time.split(":").map(Number);
      return hours * 60 + minutes;
    },

    /**
     * 分钟数转时间字符串（如 360 → "06:00"）
     * @param {number} minutes - 分钟数
     * @returns {string} 格式 "HH:mm"
     */
    minutesToTime(minutes) {
      const hours = Math.floor(minutes / 60);
      const mins = minutes % 60;
      // 补零（确保格式为 HH:mm，如 6 → "06"，5 → "05"）
      return `${hours.toString().padStart(2, "0")}:${mins
        .toString()
        .padStart(2, "0")}`;
    },
    changeTodata(val) {
      getInfoByRateId(val).then((response) => {
        this.formInfoList = response.data.map((item) => ({
          ...item,
          isEndTimeFixed: item.endTime === "24:00",
        }));
      });
    },
    getDataToSelect() {
      dataToSelect().then((response) => {
        this.dataToSelectList = response.data;
      });
    },
    addFormInfoRow(index) {
      const currentRow = this.formInfoList[index];
      const timeReg = /^([01]\d|2[0-3]):[0-5]\d$/;
      if (!currentRow.endTime || !timeReg.test(currentRow.endTime)) {
        this.$message.warning(
          "请先选择有效的结束时间（格式：HH:mm），再新增数据"
        );
        return;
      }

      const newSortNo = this.formInfoList.length + 1;
      let newRowStartTime = currentRow.endTime;
      let insertIndex = index + 1; // 插入到当前点击行的下一条

      // 新增行的初始化：endTime为null，isEndTimeFixed为false
      const newRow = {
        sortNo: newSortNo,
        templateType: "",
        startTime: newRowStartTime,
        endTime: null, // 关键：显式初始化为null
        chargeCost: null,
        serviceFee: null,
        isEndTimeFixed: false,
      };

      this.formInfoList.splice(insertIndex, 0, newRow);
      this.tableKey = new Date() + Math.random();
      this.updateAllSortNo();
    },

    deleteFormInfoRow(index) {
      // 原有逻辑：删除行 + 更新序号
      this.formInfoList.splice(index, 1);
      this.updateAllSortNo();
      // 2. 找到所有删除按钮，强制失去焦点
      const deleteBtns = document.querySelectorAll(".table-delete-btn");
      deleteBtns.forEach((btn) => {
        btn.blur(); // 每个按钮都执行失去焦点
      });
      // 新增：更新删除行的上一行和下一行的选择器配置
      if (this.formInfoList.length > 0) {
        // 更新上一行（若存在）
        if (index > 0) {
          const prevRow = this.formInfoList[index - 1];
          this.$set(prevRow, "endTime", prevRow.endTime);
        }
        // 更新原下一行（现在的index位置）
        if (index < this.formInfoList.length) {
          const currRow = this.formInfoList[index];
          this.$set(currRow, "endTime", currRow.endTime);
        }
      }

      // 原有逻辑：处理最后一行固定状态
      if (this.formInfoList.length > 0) {
        const lastRow = this.formInfoList[this.formInfoList.length - 1];
        lastRow.isEndTimeFixed = lastRow.endTime === "24:00";
      }
    },

    // 新增：批量更新所有行的sortNo（从1开始连续递增）
    updateAllSortNo() {
      this.formInfoList.forEach((row, index) => {
        row.sortNo = index + 1; // 索引+1 = 序号（1、2、3...）
      });
    },
    handleEndTimeChange(row, index) {
      // 1. 标记当前行是否固定（24:00不可改）
      row.isEndTimeFixed = row.endTime === "24:00";

      // 2. 同步更新下一行的开始时间（原有逻辑保留）
      if (index < this.formInfoList.length - 1) {
        const nextRow = this.formInfoList[index + 1];
        nextRow.startTime = row.endTime;
        // 关键：更新下一行的选择器配置（触发重新渲染）
        this.$set(nextRow, "endTime", nextRow.endTime);
      }

      // 3. 同步更新上一行的选择器配置（触发重新渲染）
      if (index > 0) {
        const prevRow = this.formInfoList[index - 1];
        this.$set(prevRow, "endTime", prevRow.endTime);
      }

      // 4. 额外校验：防止手动输入不符合规则的时间（如直接输入24:00）
      if (index < this.formInfoList.length - 1) {
        const currentEndMinutes = this.timeToMinutes(row.endTime);
        const nextEndMinutes = this.timeToMinutes(
          this.formInfoList[index + 1].endTime
        );
        if (currentEndMinutes >= nextEndMinutes) {
          // 重置为最大可选时间（下一行前30分钟）
          const maxEndTime = this.minutesToTime(nextEndMinutes - 30);

          row.endTime = maxEndTime;
          this.$message.warning(
            `当前行结束时间不能超过下一行结束时间（${
              this.formInfoList[index + 1].endTime
            }），已自动调整为${maxEndTime}`
          );
        }
      }
    },
    handleExpandChange(row, expandedRows) {
      const isExpand = expandedRows.includes(row);
      if (!isExpand) return;
      // 真实接口请求（示例）
      getInfoByRateId(row.rateId) // 传当前行的rateId
        .then((response) => {
          console.log(response.data, "response.data");
          row.tableData = response.data; // 接口返回的详情数据
          this.loadingInfo = false; // 标记加载完成
        })
        .catch((error) => {
          this.$message.error("详情加载失败，请重试");
          console.error(error);
        });
    },

    /** 提交按钮 */
    submitFormInfo(type) {
      this.form.template = type;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 调用表单的validate方法，触发所有行的校验
          this.$refs.formInfo.validate((isValid) => {
            if (isValid) {
              // 3. 新增核心校验：表格最后一条数据的结束时间必须为24:00
              const lastDetailRow =
                this.formInfoList[this.formInfoList.length - 1];
              if (!lastDetailRow || lastDetailRow.endTime !== "24:00") {
                this.$modal.msgWarning(
                  "费率明细表格最后一条数据的结束时间必须设置为24:00，请修改后再下发"
                );
                return false; // 阻断提交流程
              }
              // 校验通过：构造参数并调用接口
              const formData = {
                ...this.form,
                params: { detail: this.formInfoList }, // 表格数据作为参数
              };
              if (this.title !== "添加充电费率信息") {
                // 修改接口
                updateChargeRate(formData).then((response) => {
                  this.$modal.msgSuccess("修改成功");
                  this.open = false;
                  this.getList(); // 重新查询列表
                });
              } else {
                // 新增接口
                addChargeRate(formData).then((response) => {
                  this.$modal.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                });
              }
            } else {
              // 校验失败：无需额外操作，错误提示已自动显示
              this.$message.warning("请完善表格中所有必填项");
              return false;
            }
          });
        }
      });
    },
    handleDetail() {
      this.$router.push("/business/chargeStation/chargeRateDetail/index");
    },
    /** 查询充电费率信息列表 */
    getList() {
      this.loading = true;
      listChargeRate(this.queryParams).then((response) => {
        this.chargeRateList = response.rows
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancelInfo() {
      this.open = false;
      this.resetInfo();
    },

    resetInfo() {
      this.form = {
        rateId: null,
        rateName: null,
        versionNumber: null,
        updateStatus: null,
        deliveryStatus: null,
        appointmentStatus: null,
        deliveryType: null,
        deliveryTime: null,
        updateBy: null,
        updateTime: null,
        createBy: null,
        createTime: null,
      };
      this.resetForm("form");
      this.formInfo = {
        detailId: null,
        rateId: null,
        templateType: null,
        startTime: null,
        endTime: null,
        chargeCost: null,
        serviceFee: null,
        updateBy: null,
        updateTime: null,
        createBy: null,
        createTime: null,
        template: null,
      };
      this.resetForm("formInfo");
      this.toselectValue = "";
      this.formInfoList = [
        {
          sortNo: 1,
          templateType: "10",
          startTime: "00:00", // 初始开始时间固定
          endTime: "06:00", // 初始结束时间
          chargeCost: null,
          serviceFee: null,
          isEndTimeFixed: false, // 标记结束时间是否可修改
        },
        {
          sortNo: 2,
          templateType: "11",
          startTime: "06:00", // 初始开始时间固定
          endTime: "12:00", // 初始结束时间
          chargeCost: null,
          serviceFee: null,
          isEndTimeFixed: false, // 标记结束时间是否可修改
        },
        {
          sortNo: 3,
          templateType: "10",
          startTime: "12:00", // 初始开始时间固定
          endTime: "14:00", // 初始结束时间
          chargeCost: null,
          serviceFee: null,
          isEndTimeFixed: false, // 标记结束时间是否可修改
        },
        {
          sortNo: 4,
          templateType: "11",
          startTime: "14:00", // 初始开始时间固定
          endTime: "24:00", // 初始结束时间
          chargeCost: null,
          serviceFee: null,
          isEndTimeFixed: true, // 标记结束时间是否可修改
        },
      ];
    },
    resetDeatail() {
      this.form = {
        rateId: null,
        rateName: null,
        versionNumber: null,
        updateStatus: null,
        deliveryStatus: null,
        appointmentStatus: null,
        deliveryType: null,
        deliveryTime: null,
        updateBy: null,
        updateTime: null,
        createBy: null,
        createTime: null,
      };
      this.resetForm("formDetail");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.rateId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.resetInfo();
      this.open = true;
      this.title = "添加充电费率信息";
      this.getDataToSelect();
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.resetInfo();
      const rateId = row.rateId || this.ids;
      getChargeRate(rateId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改充电费率信息";
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const rateIds = row.rateId || this.ids;
      this.$modal
        .confirm('是否确认删除充电费率信息编号为"' + rateIds + '"的数据项？')
        .then(function () {
          return delChargeRate(rateIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "business/chargeRate/export",
        {
          ...this.queryParams,
        },
        `chargeRate_${new Date().getTime()}.xlsx`
      );
    },
  },
};
</script>
